import { createRouter, createWebHistory } from 'vue-router'
import {routes} from './routes'
import { getToken } from '@/utils/token'
import config from '@/config'
import { useUserStore } from '@/stores/user/user'

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: routes
})

router.beforeEach(async (to,from,next)=>{
	let token=getToken()
	if(to.name!=config.loginRouteName&&to.name!="404"){
		if(token){
			let store = useUserStore()
			if(!store.user._id){
				await store.refreshUserInfo()
			}
			if(store.user.userType=="0"||store.user.access.includes(to.name as string)){
				next()
			}else{
				next({name:"403"})
			}
		}else{
			next({name:config.loginRouteName})
		}
	}else{
		if(token){
			next({name:config.baseRouteName})
		}else{
			next()
		}
	}
	next()

})

export default router
